<?php
class system_user_concept extends system_concept_abstract {
	
	public function init() {
		$this->setRowClass('system_user_row');	
		$this->setModel('system_user_model', 'user');
		$this->setJoinModel('system_passport_model', 'user.id = passport.id', 'passport');
		$this->setModelCols('user', array('id', 'lang', 'nickname', 'secure', 'email', 'timezone', 'lastupip', 'lastupdate'));
		$this->setModelCols('passport', array('identity', 'credential', 'creationip', 'creationip'));
	}
	
	public function save(system_user_row $row, $options = array()) {
		if(!$row->getIdentity()) {
			throw new system_exception("PASSPORT IDENTITY is empty or Formation Error.");
		}
		if(!($passport = system_passport_instance::getRow($row->getIdentity()))) {
			throw new system_exception("PASSPORT IS NOT EXISTING.");
		}
		if(!$row->getEmail()) {
			$row->setEmail($passport->getIdentity());
		}
		if(!system_passport_instance::emailCheck($row->getEmail())) {
			throw new system_exception("Email Formation is Error.");
		}
		$row->set('id', intval($passport->getId()));
		if($this->getModel('user')->fetchRow(array('id = ?' => $row->getId()))) {
			if(!(isset($options['operation']) && $options['operation'] == 'create')) {
				if($this->getModel('user')->fetchRow(array('id != ?' => $row->getId(), 'email = ?' => $row->getEmail()))) {
					throw new system_exception("EMAIL IS ALREADY EXISTING.");
				}
				$this->getModel('user')->update($row->getModelData('user'), array('id = ?' => $row->getId()));
			}
		} else {
			if($this->getModel('user')->fetchRow(array('email = ?' => $row->getEmail()))) {
				throw new system_exception("EMAIL IS ALREADY EXISTING.");
			}
			$this->getModel('user')->insert($row->getModelData('user'));
		}
		if(isset($options['operation'])) {
			$permissions = $row->getPermissionList();
			system_db::getAdapter()->query("DELETE FROM `system_user_permission` WHERE `user_id` = '{$row->getId()}'");
			if(!empty($permissions)) {
				$sql = "REPLACE INTO `system_user_permission`(`user_id`, `group_id`) VALUES";
				$_sql = array();
				foreach($permissions AS $gid) {
					$_sql[] = "('{$row->getId()}', '{$gid}')";
				}
				system_db::getAdapter()->query($sql . implode(',', $_sql));
			}
		}
		return $row;		
	}
	
	public function delete(system_user_row $row) {
		throw new system_exception("SYSTEM USER CAN NOT BE DELETED.");
		return false;
	}

	/**
	 * 密码验证
	 * @param system_user_row $login
	 * @param unknown_type $password
	 */
	public function auth(system_user_row $row, $password) {
		return $row->getCredential() == $password;
	}

}